package com.water_work_form.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.water_work_form.entity.RecordDrugWarehouse;
import com.water_work_form.mapper.BasicFormMapper;
import com.water_work_form.mapper.RecordDrugWarehouseMapper;
import com.water_work_form.service.RecordDrugWarehouseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 记录——在线仪表药剂入库登记表 服务实现类
 * </p>
 *
 * @author xuke
 * @since 2023-09-14
 */
@Service
public class RecordDrugWarehouseServiceImpl extends ServiceImpl<RecordDrugWarehouseMapper, RecordDrugWarehouse> implements RecordDrugWarehouseService {

    @Autowired
    RecordDrugWarehouseMapper recordDrugWarehouseMapper;

    @Autowired
    BasicFormMapper basicFormMapper;

    @Value("${file.templateFilePath}")
    private String templateFilePath;

    @Value("${file.destFilePath}")
    private String destFilePath;



    /**
     * 记录——在线仪表药剂入库登记表 项目查询（三个查询项+分页）
     * @param deviceName 仪器名称（device_date） 若非空进行匹配查询
     * @param drugName 药剂名称（drug_name） 若非空进行匹配查询
     * @param status 状态（status） 若非空进行匹配查询
     * @param current 分页 当前页
     * @param size 分页 每页数据量
     * @return 返回相应数据 按照状态（status）、到货日期（arrive_date）的顺序进行升序排序
     */
    @Override
    public IPage<RecordDrugWarehouse> selectRecordDrugWarehouse(String deviceName, String drugName, String status, Integer current, Integer size){
        QueryWrapper<RecordDrugWarehouse> queryWrapper = new QueryWrapper<>();
        if(!deviceName.isEmpty()){
            queryWrapper.eq("device_name", deviceName);
        }
        if(!status.isEmpty()){
            queryWrapper.eq("status", status);
        }
        if(!drugName.isEmpty()){
            queryWrapper.eq("drug_name", drugName);
        }
        queryWrapper.orderByAsc("status", "arrive_date");
        IPage<RecordDrugWarehouse> page = new Page<>(current, size);
        return this.page(page, queryWrapper);
    }

    /**
     * 记录——在线仪表药剂入库登记表 项目查询
     * @param deviceName 仪器名称（device_name）若非空匹配查询
     * @param drugName 药剂名称（drug_name）若非空匹配查询
     * @return 返回相应数据 到货日期（arrive_date）的顺序进行升序排序
     */
    @Override
    public List<RecordDrugWarehouse> listRecordDrugWarehouse(String deviceName, String drugName){
        QueryWrapper<RecordDrugWarehouse> queryWrapper = new QueryWrapper<>();
        if(!deviceName.isEmpty()){
            queryWrapper.eq("device_name", deviceName);
        }
        if(!drugName.isEmpty()){
            queryWrapper.eq("drug_name", drugName);
        }
        queryWrapper.orderByAsc("arrive_date");
        return recordDrugWarehouseMapper.selectList(queryWrapper);
    }

    /**
     * 记录——在线仪表药剂入库登记表 基础表数据查询
     * @param name form表name
     * @return 返回对应数据 表名为键名
     */
    @Override
    public Map<String,Object> selectBasicDrugWarehouse(String name) {
        Map<String,Object> map = new HashMap<>();
        map.put("form", basicFormMapper.getOneByName(name));
        return map;
    }

    /**
     * 记录——在线仪表药剂入库登记表 列表数据导出
     * @param recordDrugWarehouseList 需要导出的数据列表
     * @param deviceName 在线仪表名称
     * @param drugName 药剂名称
     * @throws IOException 异常
     */
    @Override
    public void downloadRecordDrugWarehouse(List<RecordDrugWarehouse> recordDrugWarehouseList, String deviceName, String drugName) throws IOException {
        Map<String, Object> data = new HashMap<String, Object>();
        List<String> formatArriveDate  = new ArrayList<>();
        List<String> formatEffectiveDate  = new ArrayList<>();
        List<Map<String,Object>> formatList = new ArrayList<Map<String,Object>>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        formatArriveDate  = recordDrugWarehouseList.stream()
                .map(recordDrugWarehouse -> dateFormat.format(recordDrugWarehouse.getArriveDate()))
                .collect(Collectors.toList());
        formatEffectiveDate  = recordDrugWarehouseList.stream()
                .map(recordDrugWarehouse -> dateFormat.format(recordDrugWarehouse.getEffectiveDate()))
                .collect(Collectors.toList());
        for (int i = 0;i < recordDrugWarehouseList.size();i++){
            Map<String,Object> map = new HashMap<>();
            map.put("arriveQuantity",recordDrugWarehouseList.get(i).getArriveQuantity());
            map.put("userName",recordDrugWarehouseList.get(i).getUserName());
            map.put("arriveDate",formatArriveDate.get(i));
            map.put("effectiveDate",formatEffectiveDate.get(i));
            formatList.add(map);
        }
        data.put("lists",formatList);
        data.put("deviceName",deviceName);
        data.put("drugName",drugName);
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Configure config = Configure.builder()
                .bind("lists", policy).build();
        XWPFTemplate compile = XWPFTemplate.compile(templateFilePath + "RecordDrugWarehouse.docx",config);
        compile.render(data);
        compile.writeToFile(destFilePath + "out_recordDrugWarehouse.docx");
        compile.close();
    }


}
